package com.house.keeper.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @author zjj
 * @date 2022-05-31
 */
@Configuration
public class RedisConfig {
    @Autowired
    private RedisConnectionFactory redisConnectionFactory;

    @Bean(name = "redisTemplate")
    public  RedisTemplate<String,Object> initRedisTemplate(){
        RedisTemplate<String,Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
//        支持事务
        redisTemplate.setEnableTransactionSupport(true);

//        key序列化采用StringRedisSerializer的方式进行
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(stringRedisSerializer);
        redisTemplate.setHashKeySerializer(stringRedisSerializer);
//        value序列化采用fastjson的方式进行
        GenericFastJson2JsonRedisSerializer fastJson2JsonRedisSerializer = new GenericFastJson2JsonRedisSerializer();
        redisTemplate.setValueSerializer(fastJson2JsonRedisSerializer);
        redisTemplate.setHashValueSerializer(fastJson2JsonRedisSerializer);

//        在属性设置之后运行，初始化配置
        redisTemplate.afterPropertiesSet();

        return redisTemplate;
    }
}

